package hhm.android.main

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.os.PersistableBundle
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.igexin.sdk.PushManager
import com.tbruyelle.rxpermissions3.RxPermissions
import hhm.android.base.activity.mainActivity.ButtonResourceBean
import hhm.android.base.activity.mainActivity.MainActivity
import hhm.android.library.LogUtils.Companion.d
import hhm.android.library.bus.Bus
import hhm.android.library.bus.annotation.BusReceiver
import hhm.android.library.update.constant.UiType
import hhm.android.library.update.listener.OnBtnClickListener
import hhm.android.library.update.listener.OnInitUiListener
import hhm.android.library.update.model.UiConfig
import hhm.android.library.update.model.UpdateConfig
import hhm.android.library.update.ui.UpdateAppActivity
import hhm.android.library.update.update.UpdateAppUtils
import hhm.android.library.utils.DataStoreUtils
import hhm.android.library.utils.OnMultiClickListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.first
import siau.android.base.*
import siau.android.base.zxing.android.CaptureActivity
import siau.android.http.model.*
import siau.android.library.KeyString
import java.math.BigInteger
import java.util.*
import kotlin.collections.ArrayList

@Route(path = MAIN_ROUTER)
class MainActivity : MainActivity(), CoroutineScope by MainScope() {

    private val cameraPermissions = arrayOf(
        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA
    )
    private val locationPermissions = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    )

    private var show: LoadingDialog? = null
    private val showHandler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            show?.dismiss()
        }
    }
    private val list = ArrayList<Fragment>()
    private val l = ArrayList<ButtonResourceBean>()
    private var d: LoadingDialog? = null
    private var oldTime: Long = 0
    private val REQUEST_ENBLE_BT = 5555

    override fun onCreate(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        setTitleMainColorAndTextBlank()
        super.onCreate(savedInstanceState)

        initData()
        setData()
        check()

        val b = UpdateRequest(SBApplication.version)
        HttpHelper().getUpdateInfo(b)?.subscribe({
            async {
                val intVersion = it.version.replace(".", "").toInt()
                val notNoticeVersion = DataStoreUtils.readIntFromDataStore(KeyString.isUpdateShow).first()

                if (notNoticeVersion == intVersion) {
                    checkAd()
                    return@async
                }

                when (it.updateType) {
                    0 -> {//不需要更新
                        checkAd()
                    }
                    1 -> {//普通更新
                        val uiConfig = UiConfig().apply {
                            uiType = UiType.CUSTOM
                            customLayoutId = R.layout.dialog_update
                            updateBtnText = getString(R.string.update_right_now)
                            cancelBtnText = getString(R.string.update_not_now)
                            downloadingToastText = getString(hhm.android.library.R.string.toast_download_apk)
                            downloadingBtnText = getString(hhm.android.library.R.string.downloading)
                            downloadFailText = getString(hhm.android.library.R.string.download_fail)
                        }

                        var cb: CheckBox? = null
                        UpdateAppUtils.getInstance(this@MainActivity).apkUrl(it.link).updateTitle(getString(R.string.find_new_version)).uiConfig(uiConfig).updateContent(it.versionContent).setOnInitUiListener(object : OnInitUiListener {
                            override fun onInitUpdateUi(activity: UpdateAppActivity, view: View?, updateConfig: UpdateConfig, uiConfig: UiConfig) {
                                cb = view?.findViewById(R.id.dialog_update_cb)
                                view?.findViewById<ImageView>(R.id.dialog_update_update_x)?.setOnClickListener { _ ->
                                    if (cb?.isChecked == true) {
                                        writeVersionFunction(intVersion)
                                    }
                                    activity.checkIsClose()
                                }
                                view?.findViewById<LinearLayout>(R.id.dialog_update_not_notice_ll)?.setOnClickListener {
                                    cb?.isChecked = !cb?.isChecked!!
                                }
                                view?.findViewById<TextView>(R.id.dialog_update_version_tv)?.text = "V${it.version}"
                            }
                        }).setCancelBtnClickListener(object : OnBtnClickListener {
                            override fun onClick(): Boolean {
                                if (cb?.isChecked == true) {
                                    writeVersionFunction(intVersion)
                                }
                                checkAd()
                                return false
                            }
                        }).update()
                    }
                    else -> {
                        val uiConfig = UiConfig().apply {
                            uiType = UiType.CUSTOM
                            customLayoutId = R.layout.dialog_update
                            updateBtnText = getString(R.string.update_right_now)
                            cancelBtnText = ""
                            downloadingToastText = getString(hhm.android.library.R.string.toast_download_apk)
                            downloadingBtnText = getString(hhm.android.library.R.string.downloading)
                            downloadFailText = getString(hhm.android.library.R.string.download_fail)
                        }

                        UpdateAppUtils.getInstance(this@MainActivity).apkUrl(it.link).updateTitle(getString(R.string.find_new_version)).uiConfig(uiConfig).updateContent(it.versionContent).setOnInitUiListener(object : OnInitUiListener {
                            override fun onInitUpdateUi(activity: UpdateAppActivity, view: View?, updateConfig: UpdateConfig, uiConfig: UiConfig) {
                                view?.findViewById<ImageView>(R.id.dialog_update_update_x)?.visibility = View.GONE
                                view?.findViewById<LinearLayout>(R.id.dialog_update_not_notice_ll)?.visibility = View.GONE
                                view?.findViewById<TextView>(R.id.dialog_update_version_tv)?.text = "V${it.version}"
                            }
                        }).updateConfig(UpdateConfig(force = true)).update()
                    }
                }
            }
        }, {
            checkAd()
        })

        if (currentSelectBottom == 0 || currentSelectBottom == 2) {
            handler.sendEmptyMessageDelayed(0, 300)
        }

        SBApplication.appForeground.observe(this, {
            if (it) {
                handler.sendEmptyMessageDelayed(1, 20000)
            } else {
                handler.removeCallbacksAndMessages(null)
            }
        })

        val stringExtra = intent?.getStringExtra(KeyString.data)
        if (!TextUtils.isEmpty(stringExtra)) {
            val h5Type = intent?.getStringExtra(KeyString.H5Type)
            if (h5Type == KeyString.link) {
                linkDataAnalyse(this, stringExtra!!)
            } else if (h5Type == KeyString.scheme) {
                schemeDataAnalyse(this, stringExtra!!)
            }
        }
    }

    private fun checkAd() {
        HttpHelper().checkAd()?.subscribe({ ad ->
            if (!TextUtils.isEmpty(ad.imageUrl)) {
                getAdDialog(this, ad, object : OnMultiClickListener() {
                    override fun onMultiClick(v: View?) {
                        val r = AdvertIdModel(ad.advertId)
                        HttpHelper().hideAd(r)?.subscribe({}, {
                            showToast(it.message)
                        })

                        val tag = v?.tag as Int
                        if (tag == 1) {
                            //跳转
                            if (ad.skipType == 1) {
                                //跳转APP
                                if (ad.skipPath.startsWith("taobao")) {
                                    if (SystemUtil.isPkgInstalled(this@MainActivity, "com.taobao.taobao")) {
                                        SystemUtil.gotoShop(this@MainActivity, ad.skipPath)
                                    } else {
                                        showToast("您还没有安装淘宝客户端！")
                                    }
                                } else if (ad.skipPath.startsWith("openapp.jdmobile")) {
                                    if (SystemUtil.isPkgInstalled(this@MainActivity, "com.jingdong.app.mall")) {
                                        SystemUtil.gotoShop(this@MainActivity, ad.skipPath)
                                    } else {
                                        showToast("您还没有安装京东客户端！")
                                    }
                                }
                            } else if (ad.skipType == 2) {
                                //跳转外部浏览器
                            } else {
                                //跳转内部浏览器
                            }
                        }
                    }
                })
            }
        }, {
            showToast(it.message)
        })
    }

    private fun writeVersionFunction(intVersion: Int) {
        async {
            DataStoreUtils.writeIntToDataStore(KeyString.isUpdateShow, intVersion)
        }
    }

    private fun initData() {
        val statusBarHeightPx = getStatusBarHeightPx()
        if (!SBApplication.hasWeightMachine && !SBApplication.hasHeightMachine && !SBApplication.hasToothBrushMachine) {
            list.add(OneNoDataFragment(statusBarHeightPx))
        } else {
            list.add(OneFragment(statusBarHeightPx))
        }

        val mff = MyFlutterFragment()
        val bundle = Bundle()
        bundle.putString(KeyString.flutterview_render_mode, "texture")
        mff.arguments = bundle
        list.add(mff)

        list.add(ThreeFragment(statusBarHeightPx))
        list.add(FourFragment(statusBarHeightPx))

        l.add(ButtonResourceBean(getString(R.string.home_page), R.mipmap.icon1_unselect, R.mipmap.icon1_unselect, R.mipmap.icon1_select, false))
        l.add(ButtonResourceBean(getString(R.string.community), R.mipmap.community, R.mipmap.community, R.mipmap.community_select))
        l.add(ButtonResourceBean(getString(R.string.machine), R.mipmap.icon3_unselect, R.mipmap.icon3_unselect, R.mipmap.icon3_select))
        l.add(ButtonResourceBean(getString(R.string.mine), R.mipmap.icon4_unselect, R.mipmap.icon4_unselect, R.mipmap.icon4_select))

        if (null == SBApplication.userData) {
            async {
                DataStoreUtils.writeStringToDataStore(DataStoreUtils.TOKEN, "")
//                SBApplication.startCalculate.value = false
                SBApplication.clearBlueToothData()
            }

            handler.removeCallbacksAndMessages(null)
            KeyString.token = ""
            SBApplication.communityChildId = -1
            SBApplication.refreshMainActivityUI = false
            SBApplication.becomeCreator = false
            PushManager.getInstance().unBindAlias(this, SBApplication.userData.userAlias, true)
            ARouter.getInstance().build(LOGIN_ROUTER).withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK).navigation()
        }

        if (SBApplication.userData.children == null) {
            SBApplication.userData.children = ArrayList()
        }
        if (SBApplication.userData.deviceList == null) {
            SBApplication.userData.deviceList = ArrayList()
        }
    }

    private fun setData() {
        setFragmentAndButton(list, l, R.color.mainTextColor) { index, _ ->
            SBApplication.mainHomePageSelect = index
            if (index == 0) {
                setTitleMainColorAndTextBlank()
            } else {
                setTitleWhiteAndTextBlank()
            }

            //当被踢出家庭而且自己没有家庭，只能看消息界面
            if (SBApplication.noFamilyActivityShow && index != 1) {
                SBApplication.noFamilyActivityShow = false
                val i = Intent(this, NoFamilyDialog::class.java)
                i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(i)
            }

            //当页面在首页但是不在第一个fragment的时候 切换的时候要判断是否要刷新第一个fragment状态
            if (SBApplication.refreshMainActivityUI && index == 0) {
                //其他用户绑定或删除设备之后 收到透传消息 并且当前不在主页面，就等主页面显示之后再刷新数据
                SBApplication.refreshMainActivityUI = false
                showLoadingDialog()
                handler.removeCallbacksAndMessages(null)
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                reSetData()
            }

            if (SBApplication.becomeCreator && (index == 0 || index == 3)) {
                //其他用户绑定或删除设备之后 收到透传消息 并且当前不在主页面，就等主页面显示之后再刷新数据
                val now = currentSelectBottom
                SBApplication.becomeCreator = false
                showLoadingDialog()
                handler.removeCallbacksAndMessages(null)
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                reSetData()
                Handler().postDelayed({
                    selectPage(now, R.color.mainColor)
                    SBApplication.mainHomePageSelect = now
                }, 300)
            }

        }
        if (SBApplication.userData.unreadCount != 0) {
            changeRedTip(1, true)
        } else {
            changeRedTip(1, false)
        }
    }

    @BusReceiver
    public fun StringEvent(s: String) {
        if (s == KeyString.scanQRCode) {
            val rxPermissions = RxPermissions(this)
            rxPermissions.request(*cameraPermissions).subscribe {
                if (it) {
                    val sweep = Intent(this, CaptureActivity::class.java)
                    startActivityForResult(sweep, 1001)
                } else {
                    showToast("请先授予相机相关权限")
                }
            }
        }
        if (s == KeyString.quitFamily) {
//            SBApplication.startCalculate.value = false
            SBApplication.clearBlueToothData()
            SBApplication.communityChildId = -1
            handler.removeCallbacksAndMessages(null)
            Handler().postDelayed({
                reSetData()
            }, 300)
        }
        if (s == KeyString.createSelfFamily) {
//            SBApplication.startCalculate.value = false
            SBApplication.clearBlueToothData()
            SBApplication.communityChildId = -1
            handler.removeCallbacksAndMessages(null)
            ARouter.getInstance().build(SELECT_IDENTITY).navigation(this@MainActivity)
        }
    }

    /**
     * 1.从微信被邀请过来之后 没有自己的家庭，切换家庭的时候 创建自己家庭流程会走 毕竟那个时候MainActivity没有关闭
     *   if (s == KeyString.createSelfFamily) {
     *       ARouter.getInstance().build(SELECT_IDENTITY).navigation(this@MainActivity)
     *   }
     *
     * 2.点击推送可能会走
     */
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        val type = intent?.getStringExtra(KeyString.type)
        if (KeyString.pushMessage == type) {//注释2
            ARouter.getInstance().build(MESSAGE_ROUTER).navigation()
        } else if (KeyString.refreshMainDevice == type) {
            if (currentSelectBottom == 0) {
                //其他用户绑定或删除设备之后 收到透传消息 并且当前在主页面，就直接刷新数据
                showLoadingDialog()
                handler.removeCallbacksAndMessages(null)
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                reSetData()
            } else {
                SBApplication.refreshMainActivityUI = true
            }
        } else if (KeyString.becomeCreator == type) {
            if (currentSelectBottom == 0 || currentSelectBottom == 3) {
                val now = currentSelectBottom
                showLoadingDialog()
                handler.removeCallbacksAndMessages(null)
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                reSetData()
                Handler().postDelayed({
                    selectPage(now, R.color.mainColor)
                    SBApplication.mainHomePageSelect = now
                }, 300)
            } else {
                SBApplication.becomeCreator = true
            }
        } else if (KeyString.community == type) {
            val ff = list[1] as MyFlutterFragment
            ff.sendMessageToFlutter(intent.getStringExtra(KeyString.data)!!)
        } else {//注释1
            reSetData()
        }
    }

    fun changeFamily(id: Int) {
//        SBApplication.startCalculate.value = false
        SBApplication.clearBlueToothData()
        SBApplication.communityChildId = -1
        handler.removeCallbacksAndMessages(null)
        val loadBuilder = LoadingDialog.Builder(this).setShowMessage(false).setCancelable(false).setCancelOutside(false)
        d = loadBuilder.create()
        val r = FamilyIdModel(id)
        HttpHelper().changeFamily(r)?.subscribe({
            SBApplication.userData = it
            SBApplication.hasWeightMachine = false
            SBApplication.hasHeightMachine = false
            SBApplication.hasToothBrushMachine = false
            it.deviceList?.forEach { d ->
                when (d.deviceType) {
                    1 -> {
                        SBApplication.hasWeightMachine = true
                    }
                    2 -> {
                        SBApplication.hasHeightMachine = true
                    }
                    3 -> {
                        SBApplication.hasToothBrushMachine = true
                    }
                }
            }
            if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                handler.sendEmptyMessage(1)
            }
            d?.hide()

            reSetData()
            SBApplication.startShowChangeFamilySheet = false
        }, {
            d?.hide()
            showToast(it.message)
            SBApplication.startShowChangeFamilySheet = false
        })
    }

    private fun reSetData() {
        list.clear()
        l.clear()
        setTitleMainColorAndTextBlank()
        initData()
        reSetData(list, l, R.color.mainTextColor) { index, _ ->
            SBApplication.mainHomePageSelect = index
            if (index == 0) {
                setTitleMainColorAndTextBlank()
            } else {
                setTitleWhiteAndTextBlank()
            }

            //当被踢出家庭而且自己没有家庭，只能看消息界面
            if (SBApplication.noFamilyActivityShow && index != 1) {
                SBApplication.noFamilyActivityShow = false
                val i = Intent(this, NoFamilyDialog::class.java)
                i.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(i)
            }

            //当页面在首页但是不在第一个fragment的时候 切换的时候要判断是否要刷新第一个fragment状态
            if (SBApplication.refreshMainActivityUI && index == 0) {
                //其他用户绑定或删除设备之后 收到透传消息 并且当前不在主页面，就等主页面显示之后再刷新数据
                SBApplication.refreshMainActivityUI = false
                showLoadingDialog()
                handler.removeCallbacksAndMessages(null)
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                reSetData()
            }

            if (SBApplication.becomeCreator && (index == 0 || index == 3)) {
                //其他用户绑定或删除设备之后 收到透传消息 并且当前不在主页面，就等主页面显示之后再刷新数据
                val now = currentSelectBottom
                SBApplication.becomeCreator = false
                showLoadingDialog()
                handler.removeCallbacksAndMessages(null)
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                reSetData()
                Handler().postDelayed({
                    selectPage(now, R.color.mainColor)
                    SBApplication.mainHomePageSelect = now
                }, 300)
            }

        }
        if (SBApplication.userData.unreadCount != 0) {
            changeRedTip(1, true)
        } else {
            changeRedTip(1, false)
        }
        hideLoadingDialog()
        check()
    }

    private fun check() {
        if (SBApplication.userData.userStatus == 3) {
            getBindIdentityDialog(this, object : OnMultiClickListener() {
                override fun onMultiClick(v: View?) {
                    ARouter.getInstance().build(SELECT_IDENTITY).withInt(KeyString.type, 1).navigation(this@MainActivity, 1002)
                }
            })
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENBLE_BT && resultCode == RESULT_OK) {
            SBApplication.getBlueToothUtils().pairBlueTooth()
        } else if (requestCode == 1001 && resultCode == RESULT_OK) {//扫码

            val loadBuilder = LoadingDialog.Builder(this).setShowMessage(false).setCancelable(false).setCancelOutside(false)
            d = loadBuilder.create()
            d!!.show()

            //返回的文本内容
            val content = data!!.getStringExtra("codedContent")

            //https://www.baidu.com?userId=6&familyId=8
            val s = content!!.split("?")
            val split1 = s[1]
            val ds = split1.split("&")
            val userId = ds[0].replace("userId=", "")
            val familyId = ds[1].replace("familyId=", "")
            val r = AddFamilyRequest(userId.toInt(), familyId.toInt())
            HttpHelper().scanAddFamily(r)?.subscribe({ it ->
                SBApplication.clearBlueToothData()
                SBApplication.communityChildId = -1
                SBApplication.userData = it
                SBApplication.hasWeightMachine = false
                SBApplication.hasHeightMachine = false
                SBApplication.hasToothBrushMachine = false
//                SBApplication.startCalculate.value = false
                handler.removeCallbacksAndMessages(null)
                SBApplication.userData.deviceList?.forEach { d ->
                    when (d.deviceType) {
                        1 -> {
                            SBApplication.hasWeightMachine = true
                        }
                        2 -> {
                            SBApplication.hasHeightMachine = true
                        }
                        3 -> {
                            SBApplication.hasToothBrushMachine = true
                        }
                    }
                }
                if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                    handler.sendEmptyMessage(1)
                }
                d?.hide()
                reSetData()

            }, {
                d?.hide()
                showToast(it.message)
            })
        }
        if (requestCode == 1002) {
            if (resultCode == RESULT_OK) {
                SBApplication.userData.userStatus = 1
            } else {
                check()
            }
        }
    }

    override fun onBackPressed() {
        val nowTime = Date().time
        if (nowTime - oldTime <= 3000) {
            if (handler != null) {
                handler.removeCallbacksAndMessages(null)
            }
            super.onBackPressed()
        } else {
            oldTime = nowTime
            showToast(getString(R.string.press_and_quit_seven_bubble))
        }
    }

    private fun tryBindBlueTooth() {
        if (SBApplication.userData.deviceList?.size!! > 0) {
            SBApplication.getBlueToothUtils()

            if (SBApplication.getBlueToothUtils().mBluetoothAdapter == null) {
                showToast("当前设备不支持蓝牙")
                return
            }

            val rxPermissions = RxPermissions(this)
            rxPermissions.request(*locationPermissions).subscribe {
                if (it) {
                    // 没有打开蓝牙
                    if (!SBApplication.getBlueToothUtils().mBluetoothAdapter.isEnabled) {
                        val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                        startActivityForResult(enableBtIntent, REQUEST_ENBLE_BT)
                    } else {
                        SBApplication.getBlueToothUtils().pairBlueTooth()
                    }
                } else {
                    showToast("蓝牙功能需要获取GPS位置权限才能扫描到设备")
                }
            }
        }
    }

    private val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                tryBindBlueTooth()
            } else if (msg.what == 1) {
                looperScanBluetooth()
                sendEmptyMessageDelayed(1, 20000)
            }
        }
    }

    private fun looperScanBluetooth() {
        if (SBApplication.userData.deviceList?.size!! > 0) {
            SBApplication.getBlueToothUtils()

            if (SBApplication.getBlueToothUtils().mBluetoothAdapter == null) {
                return
            }

            if (SBApplication.getBlueToothUtils().mBluetoothAdapter.isEnabled) {
                SBApplication.getBlueToothUtils().pairBlueTooth()
            }
        }
    }

    protected fun showLoadingDialog() {
        val loadBuilder = LoadingDialog.Builder(this).setShowMessage(false).setCancelable(false).setCancelOutside(false)
        show = loadBuilder.create()
        show?.show()
    }

    protected fun hideLoadingDialog() {
        showHandler.sendEmptyMessageDelayed(0, 300)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (handler != null) {
            handler.removeCallbacksAndMessages(null)
        }
    }

    override fun finish() {
        super.finish()
        Bus.getDefault().unregister(this)
        if (handler != null) {
            handler.removeCallbacksAndMessages(null)
        }
    }

    override fun onResume() {
        super.onResume()

        if (SBApplication.refreshMainActivityUI && currentSelectBottom == 0) {
            //其他用户绑定或删除设备之后 收到透传消息 并且当前不在主页面，就等主页面显示之后再刷新数据
            SBApplication.refreshMainActivityUI = false
            showLoadingDialog()
            handler.removeCallbacksAndMessages(null)
            SBApplication.hasWeightMachine = false
            SBApplication.hasHeightMachine = false
            SBApplication.hasToothBrushMachine = false
            SBApplication.userData.deviceList?.forEach { d ->
                when (d.deviceType) {
                    1 -> {
                        SBApplication.hasWeightMachine = true
                    }
                    2 -> {
                        SBApplication.hasHeightMachine = true
                    }
                    3 -> {
                        SBApplication.hasToothBrushMachine = true
                    }
                }
            }
            if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                handler.sendEmptyMessage(1)
            }
            reSetData()

        }

        if (SBApplication.becomeCreator && (currentSelectBottom == 0 || currentSelectBottom == 3)) {
            //其他用户绑定或删除设备之后 收到透传消息 并且当前不在主页面，就等主页面显示之后再刷新数据
            val now = currentSelectBottom
            SBApplication.becomeCreator = false
            showLoadingDialog()
            handler.removeCallbacksAndMessages(null)
            SBApplication.hasWeightMachine = false
            SBApplication.hasHeightMachine = false
            SBApplication.hasToothBrushMachine = false
            SBApplication.userData.deviceList?.forEach { d ->
                when (d.deviceType) {
                    1 -> {
                        SBApplication.hasWeightMachine = true
                    }
                    2 -> {
                        SBApplication.hasHeightMachine = true
                    }
                    3 -> {
                        SBApplication.hasToothBrushMachine = true
                    }
                }
            }
            if (SBApplication.hasWeightMachine || SBApplication.hasHeightMachine || SBApplication.hasToothBrushMachine) {
                handler.sendEmptyMessage(1)
            }
            reSetData()
            Handler().postDelayed({
                selectPage(now, R.color.mainColor)
                SBApplication.mainHomePageSelect = now
            }, 300)
        }
    }

    override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
    }

    override fun onSaveInstanceState(outState: Bundle) {
    }
}